Import('env', 'install_perms')
from os.path import join, basename
from glob import glob
import subprocess


# Build: for all .po source files, normally build binary .mo message
# catalogs ready for installation.

languages = []
for src in env.Glob('*.po'):
    lang = basename(str(src))[:-3]
    languages.append(lang)
    dst = join(lang, "LC_MESSAGES", 'mypaint.mo')
    env.Command(dst, src, 'msgfmt $SOURCE -o $TARGET')


# Install: normally, install the generated binary catalogs

for lang in languages:
    install_perms(env, '$prefix/share/locale/%s/LC_MESSAGES' % lang,
                 '%s/LC_MESSAGES/mypaint.mo' % lang)


# Alternatively, when scons is called with the translate=* option,
# forgo the usual build and install, and operate in a special
# translation maintenance mode instead.
#
#  translate=pot
#     Generate template for .po files (mypaint.pot) only
#     Use when starting to translate for a new language.
#  translate=LANGCODE
#     Update src .po file for just one language (updates mypaint.pot,
#     then merges fresh/updated strings into LANGCODE.po)
#     Individual translators can do just this for their language
#     if they want to keep things updated.
#  translate=all
#     Update source .po files for all languages
#     Used by core MyPaint devs when starting a string freeze


def build_potfiles_in(target, source, env):
    """Builds POTFILES.in, for intltool-update to chew on."""

    # Begin listing Python files which import gettext-related modules.
    # intltool-update knows about python code using syntax like the
    # C macros.
    pfi_lines = []
    pfi_lines.extend(subprocess.check_output([
        "git", "grep",
        "--full-name",
        "--files-with-matches", "^from gettext import",
        "..",
    ]).split("\n"))
    pfi_lines.extend(subprocess.check_output([
        "git", "grep",
        "--full-name",
        "--files-with-matches", "^from lib.gettext import",
        "..",
    ]).split("\n"))

    # Builder XML and resource definitions are converted to a .h file
    # in po/tmp which intltool-update can then work on.
    ui_files = []
    ui_files.append("../gui/resources.xml")
    ui_files.extend(glob("../gui/*.glade"))
    for ui_file in ui_files:
        subprocess.check_call([
            "intltool-extract",
            "--local",
            "--type=gettext/glade",
            ui_file,
        ])
        tmp_file = "po/tmp/%s.h" % (basename(ui_file),)
        pfi_lines.append(tmp_file)

    # Dump out a nicely sorted POTFILES.in
    pfi_fp = open("POTFILES.in", "w")
    pfi_lines.sort()
    for line in pfi_lines:
        pfi_fp.write(line + "\n")
    pfi_fp.close()
    return 0


# Only clean up po/tmp/ (made by build_potfiles_in()) in normal -c runs.
# The maintainer should be able to inspect its contents after running
# in translation maintenance mode.
env.Clean(".", ["tmp"])


lang = ARGUMENTS.get('translate')
if lang:
    if lang == 'all':
        # For programmers and program maintainers.
        # Update the .pot file and all po/*.po.
        # Use this after changing any source string.
        # WebLate will receive a new template and flag string changes
        # for review by translators.
        env.Execute(build_potfiles_in)
        env.Execute([
            ["intltool-update", "-g", "mypaint", "--pot"],
        ])
        translate = languages
    elif lang == 'pot':
        # For programmers and program maintainers.
        # Update the .pot file only.
        # Handy for doing local diffs,
        # but it's best not to commit alone - .po files on
        # WebLate sould be kept in sync with their .pot.
        env.Execute(build_potfiles_in)
        env.Execute([
            ["intltool-update", "-g", "mypaint", "--pot"],
        ])
        translate = []
    else:
        # For individual language maintainers.
        # Update the named language only from the most recently .pot
        # and do not update the .pot file itself.
        translate = [lang]
    for lang in translate:
        env.Execute([
            ["intltool-update", "-g", "mypaint", "--dist", lang],
        ])
    # Exit now, and don't build or install any regular targets
    Exit()


Return('languages')

# vim:syntax=python
